<template>
  <div class="raceCreate">
    <div class="r-header">
      <div class="r-h-title">
        <i class="iconfont icon-chuangjianrenwu"></i>{{ route.name == "raceedit" ? "编辑比赛" : "创建比赛" }}
      </div>
    </div>
    <n-form class="form" :model="raceData" :rules="rules" ref="formRef">
      <n-form-item path="title" label="比赛标题">
        <n-input placeholder="比赛标题" v-model:value="raceData.title"></n-input>
      </n-form-item>
      <n-form-item label="比赛描述">
        <v-md-editor class="mdEdit" :left-toolbar="toolbar" height="300px" :disabled-menus="[]"
          v-model="raceData.description"></v-md-editor>
      </n-form-item>
      <div class="private">
        <n-form-item path="auth" label="比赛权限" class="p-item">
          <n-select placeholder="比赛权限" :options="raceAuth" v-model:value="raceData.auth"></n-select>
        </n-form-item>
        <n-form-item path="pwd" label="比赛密码" class="p-item" v-show="raceData.auth == 1">
          <n-input placeholder="比赛密码" v-model:value="raceData.pwd" type="password" clearable
            show-password-on="mousedown"></n-input>
        </n-form-item>
      </div>
      <div class="private">
        <n-form-item path="type" label="比赛类型" class="p-item">
          <n-select placeholder="比赛类型" :options="raceType" v-model:value="raceData.type"
            :disabled="route.name == 'raceedit'"></n-select>
        </n-form-item>
        <n-form-item path="groupUserMaxCount" label="团队人数上限" class="p-item" v-show="raceData.type == 1">
          <n-input-number :min="1" :max="100" placeholder="团队人数上限"
            v-model:value="raceData.groupUserMaxCount"></n-input-number>
        </n-form-item>
        <n-form-item path="groupRankType" label="团队排名方式" class="p-item"
          v-show="raceData.type == 1 && raceData.format != 0">
          <n-select :options="teamRank" placeholder="团队排名方式" v-model:value="raceData.groupRankType"></n-select>
        </n-form-item>
      </div>
      <div class="datebox" v-show="raceData.type == 1">
        <n-form-item path="regStartTime" label="比赛报名时间(开始)" class="date">
          <n-date-picker v-model:value="raceData.regStartTime" value-format="yyyy.MM.dd HH:mm:ss" type="datetime"
            placeholder="开始时间"></n-date-picker>
        </n-form-item>
        <n-form-item path="regEndTime" label="比赛报名时间(结束)" class="date">
          <n-date-picker v-model:value="raceData.regEndTime" value-format="yyyy.MM.dd HH:mm:ss" type="datetime"
            placeholder="结束时间"></n-date-picker>
        </n-form-item>
      </div>
      <div class="datebox">
        <n-form-item path="startTime" label="比赛时间(开始)" class="date">
          <n-date-picker v-model:value="raceData.startTime" value-format="yyyy.MM.dd HH:mm:ss" type="datetime"
            placeholder="开始时间"></n-date-picker>
        </n-form-item>
        <n-form-item path="endTime" label="比赛时间(结束)" class="date">
          <n-date-picker v-model:value="raceData.endTime" value-format="yyyy.MM.dd HH:mm:ss" type="datetime"
            placeholder="结束时间"></n-date-picker>
        </n-form-item>
        <n-form-item label="比赛时长" class="date">
          <n-input disabled placeholder="比赛时长" v-model:value="raceData.duration"></n-input>
        </n-form-item>
      </div>
      <div class="format">
        <n-form-item path="format" label="赛制" class="f-item">
          <n-radio-group v-model:value="raceData.format" :disabled="route.name == 'raceedit'">
            <n-space>
              <n-radio :value="0">ACM</n-radio>
              <n-radio :value="1">OI</n-radio>
              <n-radio :value="2">IOI</n-radio>
              <n-radio :value="3">天梯</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item class="f-item" path="oiIoiRankType" label="排名方式"
          v-show="raceData.format == 1 || raceData.format == 2">
          <n-select placeholder="排名方式" :options="oiRankWay" v-model:value="raceData.oiIoiRankType"></n-select>
        </n-form-item>
        <n-form-item class="f-item" path="acmTimePenalty" label="罚时设置" v-show="raceData.format == 0">
          <n-input-number placeholder="罚时设置" v-model:value="raceData.acmTimePenalty"></n-input-number>
        </n-form-item>
        <n-form-item class="f-item" path="acmTimePenalty" label="天梯是否允许抢分" v-show="raceData.format == 3">
          <n-switch v-model:value="raceData.tiantiSnatchPoints" class="s-b-switch" :checked-value="1"
            :unchecked-value="0">
            <template #checked> 不允许 </template>
            <template #unchecked> 允许 </template>
          </n-switch>
        </n-form-item>
      </div>
      <n-form-item label="天梯阶段分数" v-show="raceData.format == 3">
        <div class="tianti2">
          <el-table border :data="raceData.tiantiStageConfig.stage" stripe class="table">
            <el-table-column type="index" label="阶段" align="center" width="160">
              <template #default="scoped">
                <n-tag round type="success">第 {{ scoped.$index + 1 }} 阶段</n-tag>
              </template>
            </el-table-column>
            <el-table-column type="index" label="阶段名称" align="center" width="160">
              <template #default="scoped">
                <n-input size="small" v-model:value="scoped.row.name" placeholder="" maxlength="10"></n-input>
              </template>
            </el-table-column>
            <el-table-column label="阶段分数" align="center">
              <template #default="scoped">
                <n-input-number class="input-number" size="small" v-model:value="scoped.row.score" :min="1" clearable
                  placeholder="阶段分数">
                </n-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scoped">
                <n-button class="btn" type="error" round size="tiny" @click="deltitianStage(scoped.$index)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="btns">
            <n-button class="btn" type="success" round size="small" @click="appendtitianStage">
              <i class="iconfont icon-tianjia"></i>添加阶段配置
            </n-button>
          </div>
        </div>
      </n-form-item>
      <n-form-item label="天梯先锋分数" v-show="raceData.format == 3">
        <div class="tianti2">
          <el-table border :data="raceData.tiantiStageConfig.personalScore" stripe class="table">
            <el-table-column type="index" label="序号" align="center" width="160">
              <template #default="scoped">
                <n-tag round type="success">{{ scoped.$index + 1 }}</n-tag>
              </template>
            </el-table-column>
            <el-table-column label="先锋人数" align="center">
              <template #default="scoped">
                <n-input-number class="input-number" size="small" v-model:value="scoped.row.num" :min="1" :max="100"
                  clearable placeholder="先锋人数">
                </n-input-number>
              </template>
            </el-table-column>
            <el-table-column label="先锋分数" align="center">
              <template #default="scoped">
                <n-input-number class="input-number" size="small" v-model:value="scoped.row.score" :min="1" :max="999"
                  clearable placeholder="先锋分数">
                </n-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scoped">
                <n-button class="btn" type="error" round size="tiny" @click="deltitianPersonal(scoped.$index)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="btns">
            <n-button class="btn" type="success" round size="small" @click="appendtitianPersonal">
              <i class="iconfont icon-tianjia"></i>添加先锋设置
            </n-button>
          </div>
        </div>
      </n-form-item>

      <div class="lockRank">
        <n-form-item class="l-item" label="排行榜设置">
          <n-switch v-model:value="raceData.lockRank" class="s-b-switch" :rail-style="railStyle" :checked-value="1"
            :unchecked-value="0">
            <template #checked> 实时更新 </template>
            <template #unchecked> 定时封榜 </template>
          </n-switch>
        </n-form-item>
        <n-form-item path="lockRankTime" class="l-item" label="封榜开始时间" v-if="raceData.lockRank == 0">
          <n-date-picker value-format="yyyy.MM.dd HH:mm:ss" type="datetime" placeholder="封榜开始时间"
            v-model:value="raceData.lockRankTime"></n-date-picker>
        </n-form-item>
      </div>
      <div class="pane">
        <n-form-item label="赛外榜单是否可见" class="pane-item">
          不可见&emsp13;
          <n-switch v-model:value="raceData.isShowRank" class="s-b-switch" :checked-value="0" :unchecked-value="1">
          </n-switch>
          &emsp13;可见
        </n-form-item>
      </div>
      <div class="pane">
        <n-form-item label="赛后是否重进" class="pane-item">
          否&emsp13;
          <n-switch v-model:value="raceData.allowEndEntry" class="s-b-switch" :checked-value="1" :unchecked-value="0">
          </n-switch>
          &emsp13;是
        </n-form-item>
      </div>
      <n-form-item label="排行榜显示用户">
        <n-radio-group v-model:value="raceData.rankShowName">
          <n-space>
            <n-radio value="username">不显示</n-radio>
            <n-radio value="nickname">昵称</n-radio>
            <n-radio value="realname">真实姓名</n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <div class="awards">
        <n-form-item label="个人比赛奖项">
          <n-select placeholder="个人比赛奖项" class="short" :options="awards" v-model:value="raceData.accountAwardType"
            @update:value="AwardTypeChange()"></n-select>
        </n-form-item>
        <div v-show="raceData.accountAwardType == 1 || raceData.accountAwardType == 2" class="awardConfig">
          <el-table border :data="raceData.accountAwardConfig" stripe class="table">
            <el-table-column prop="level" label="等级" align="center" />
            <el-table-column label="奖项名称" align="center">
              <template #default="scoped">
                <n-input size="small" v-model:value="scoped.row.name" maxlength="10" clearable
                  placeholder="奖项名称"></n-input>
              </template>
            </el-table-column>
            <el-table-column prop="backColor" label="背景颜色" align="center">
              <template #default="scoped">
                <el-color-picker v-model="scoped.row.backColor" />
              </template>
            </el-table-column>
            <el-table-column prop="data" align="center" :label="raceData.accountAwardType == 1
              ? '占比(%)'
              : raceData.accountAwardType == 2
                ? '人数(个)'
                : ''
              ">
              <template #default="scoped">
                <n-input-number :min="1" size="small" v-model:value="scoped.row.data" placeholder=""></n-input-number>
              </template></el-table-column>
            <el-table-column prop="name" label="操作" align="center">
              <template #default="scoped">
                <n-button class="btn" type="error" round size="tiny" @click="delAward(scoped.row.level, 0)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="right-btns">
            <n-button class="btn" type="success" round size="small" @click="appendAward(0)">
              <i class="iconfont icon-tianjia"></i>添加奖项
            </n-button>
          </div>
        </div>
      </div>
      <div class="awards" v-show="raceData.type == 1">
        <n-form-item label="团队比赛奖项">
          <n-select placeholder="团队比赛奖项" class="short" :options="awards" v-model:value="raceData.groupAwardType"
            @update:value="AwardTypeChange()"></n-select>
        </n-form-item>
        <div v-show="raceData.groupAwardType == 1 || raceData.groupAwardType == 2" class="awardConfig">
          <el-table border :data="raceData.groupAwardConfig" stripe class="table">
            <el-table-column prop="level" label="等级" align="center" />
            <el-table-column label="奖项名称" align="center">
              <template #default="scoped">
                <n-input size="small" v-model:value="scoped.row.name" maxlength="10" clearable
                  placeholder="奖项名称"></n-input>
              </template>
            </el-table-column>
            <el-table-column prop="backColor" label="背景颜色" align="center">
              <template #default="scoped">
                <el-color-picker v-model="scoped.row.backColor" />
              </template>
            </el-table-column>
            <el-table-column prop="data" align="center" :label="raceData.groupAwardType == 1
              ? '占比(%)'
              : raceData.groupAwardType == 2
                ? '队伍(个)'
                : ''
              ">
              <template #default="scoped">
                <n-input-number :min="1" size="small" v-model:value="scoped.row.data" placeholder=""></n-input-number>
              </template></el-table-column>
            <el-table-column prop="name" label="操作" align="center">
              <template #default="scoped">
                <n-button class="btn" type="error" round size="tiny" @click="delAward(scoped.row.level, 1)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="right-btns">
            <n-button class="btn" type="success" round size="small" @click="appendAward(1)">
              <i class="iconfont icon-tianjia"></i>添加奖项
            </n-button>
          </div>
        </div>
      </div>
      <div class="star" v-if="raceData.id?.length > 0 && raceData.id">
        <n-form-item label="打星用户">
          <n-tag round class="tag" size="small" v-for="item in stars" :key="item.id" closable
            @close="handleClose(item.username, 0)">
            <n-ellipsis style="max-width: 60px">
              {{ item.username }}
            </n-ellipsis>
          </n-tag>
          <n-button size="small" type="success" round @click="(isShowUsers = true), getUserInfoList()">
            <i class="iconfont icon-tianjia"></i>
          </n-button>
        </n-form-item>
      </div>
      <div class="star" v-if="raceData.id?.length > 0 && raceData.id && raceData.type == 1">
        <n-form-item label="打星团队">
          <n-tag round class="tag" size="small" v-for="item in starsGroup" :key="item.id" closable
            @close="handleClose(item.id, 1)">
            <n-ellipsis style="max-width: 60px">
              {{ item.name }}
            </n-ellipsis>
          </n-tag>
          <n-button size="small" type="success" round @click="(isShowGroups = true), getGroupList()">
            <i class="iconfont icon-tianjia"></i>
          </n-button>
        </n-form-item>
      </div>
    </n-form>
    <div class="footer">
      <n-button class="save" type="success" size="small" @click="handleValidateButtonClick">保存</n-button>
    </div>
    <el-drawer v-model="isShowUsers" :show-close="false" direction="rtl" class="drawer" size="50%">
      <template #header="{ close, titleId, titleClass }">
        <h1 :id="titleId" :class="titleClass">用户列表</h1>
        <n-button size="small" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="users.records">
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center">
          <template #default="scoped">{{ scoped.row.number || "--" }}</template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" align="center">
          <template #default="scoped">{{
            scoped.row.realName || "--"
          }}</template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" align="center">
          <template #default="scoped">{{
            scoped.row.nickname || "--"
          }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <el-tooltip content="添加用户" placement="top">
              <n-button size="tiny" type="success" @click="appendToStar(scoped.row, 0)">
                <i class="iconfont icon-tijiao1"></i>
              </n-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-pagination class="pagination" :page-sizes="[20, 50, 99]" background small layout="prev, pager, next,sizes"
          :total="Number(users.total)" v-model:current-page="searchParams.pageNum"
          v-model:page-size="searchParams.pageSize" />
      </div>
    </el-drawer>
    <el-drawer v-model="isShowGroups" :show-close="false" direction="rtl" class="drawer" size="50%">
      <template #header="{ close, titleId, titleClass }">
        <h1 :id="titleId" :class="titleClass">团队列表</h1>
        <n-button size="small" round strong secondary type="error" @click="close">
          <i class="iconfont icon-chahao1"></i>
        </n-button>
      </template>
      <el-table class="table" :data="groups.records">
        <el-table-column type="index" label="序号" align="center" width="100%" :index="indexMethod"></el-table-column>
        <el-table-column prop="name" label="团队名称" align="center"></el-table-column>
        <el-table-column prop="leader" label="队长" align="center">
          <template #default="scoped">{{ scoped.row.leader || "--" }}</template>
        </el-table-column>
        <el-table-column label="队伍人数" align="center">
          <template #default="scoped">
            {{
              scoped.row.groupUsers.length || "0"
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <el-tooltip content="添加团队" placement="top">
              <n-button size="tiny" type="success" @click="appendToStar(scoped.row, 1)">
                <i class="iconfont icon-tijiao1"></i>
              </n-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer">
        <el-pagination class="pagination" :page-sizes="[20, 50, 99]" background small layout="prev, pager, next,sizes"
          :total="Number(groups.total)" v-model:current-page="searchParams2.pageNum"
          v-model:page-size="searchParams2.pageSize" />
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from "vue"
import { debounce } from "@/utils/global.js"
import { ElMessage } from "element-plus"
import {
  appendRaceAPI,
  updateRaceAPI,
  getRaceUsersAPI,
  getRaceDetailAPI,
  getGroupListAPI
} from "@/api/adminAPI/adminAPI"
import { useRoute, useRouter } from "vue-router"

const toolbar =
  "undo redo clear | h bold italic strikethrough quote | ul ol table hr | link tip code  | emoji"
const router = useRouter()
const route = useRoute()
const railStyle = ({ focused, checked }) => {
  const style = {}
  if (checked) {
    style.background = "rgba(235,169,46,0.8)"
    if (focused) {
      style.boxShadow = "0 0 0 2px #2080f040"
    }
  } else {
    style.background = "rgba(60,128,242,0.8)"
    if (focused) {
      style.boxShadow = "0 0 0 2px #2080f040"
    }
  }
  return style
}

const raceAuth = [
  {
    label: "公开赛",
    value: 0,
  },
  {
    label: "私有赛",
    value: 1,
  },
  {
    label: "保护赛",
    value: 2,
  },
]

const raceType = [
  {
    label: "单人赛",
    value: 0,
  },
  {
    label: "团队赛",
    value: 1,
  },
]
const awards = [
  {
    label: "不设置",
    value: 0,
  },
  {
    label: "设置占比",
    value: 1,
  },
  {
    label: "设置人数",
    value: 2,
  },
]
const teamRank = [
  {
    label: "总分排名",
    value: "Total",
  },
  {
    label: "平均分排名",
    value: "Average",
  },
]
const oiRankWay = [
  {
    label: "最新提交",
    value: "Recent",
  },
  {
    label: "最高提交",
    value: "Highest",
  },
]

const raceData = ref({
  id: "",
  title: "",
  type: 0,
  format: 1,
  description: "",
  source: "",
  auth: 0,
  pwd: "",
  regStartTime: null,
  regEndTime: null,
  startTime: null,
  endTime: null,
  lockRank: 0,
  lockRankTime: null,
  visible: 0,
  rankShowName: "username",
  isShowRank: 1,
  starAccount: [], //用户id的json数组
  starGroup: [],//团队id的json数组
  groupUserMaxCount: 10,
  groupRankType: "Total",
  oiIoiRankType: "Recent",
  accountAwardType: 0,
  accountAwardConfig: [
    { backColor: "#F2EF09", data: 10, level: "1", name: "金牌" },
    { backColor: "#B1B2A8", data: 20, level: "2", name: "银牌" },
    { backColor: "#D4964B", data: 30, level: "3", name: "铜牌" },
  ], // 奖项设置json,backColor是背景颜色,data是人数或者百分比（只用传数值即可,前端展示可以变化）,level就是等级（从小到大）,name就是奖牌名称
  groupAwardType: 0,
  groupAwardConfig: [
    { backColor: "#F2EF09", data: 10, level: "1", name: "金牌" },
    { backColor: "#B1B2A8", data: 20, level: "2", name: "银牌" },
    { backColor: "#D4964B", data: 30, level: "3", name: "铜牌" },
  ],
  allowEndEntry: 0,
  tiantiStageConfig: {
    stage: [
      {
        score: 20
      },
      {
        score: 30
      }
    ],
    personalScore: [
      {
        num: 1,
        score: 50
      },
      {
        num: 2,
        score: 30
      },
      {
        num: 3,
        score: 10
      }
    ]
  },
  duration: "",
  acmTimePenalty: 20,
  tiantiSnatchPoints: 1,
})
const raceOriginData = {
  title: "",
  type: 0,
  format: 0,
  description: "",
  source: "",
  auth: 0,
  pwd: "",
  regStartTime: null,
  regEndTime: null,
  startTime: null,
  endTime: null,
  lockRank: 0,
  lockRankTime: null,
  visible: 0,
  rankShowName: "username",
  isShowRank: 1,
  starAccount: [], //用户id的json数组
  starGroup: [],//团队id的json数组
  groupUserMaxCount: 10,
  groupRankType: "Total",
  oiIoiRankType: "Recent",
  accountAwardType: 0,
  accountAwardConfig: [
    { backColor: "#222222", data: 10, level: "1", name: "金牌" },
    { backColor: "#222222", data: 20, level: "2", name: "银牌" },
    { backColor: "#222222", data: 30, level: "3", name: "铜牌" },
  ], // 奖项设置json,backColor是背景颜色,data是人数或者百分比（只用传数值即可,前端展示可以变化）,level就是等级（从小到大）,name就是奖牌名称
  groupAwardType: 0,
  groupAwardConfig: [
    { backColor: "#F2EF09", data: 10, level: "1", name: "金牌" },
    { backColor: "#B1B2A8", data: 20, level: "2", name: "银牌" },
    { backColor: "#D4964B", data: 30, level: "3", name: "铜牌" },
  ],
  tiantiStageConfig: {
    stage: [
      {
        nama: '',
        score: 20
      },
      {
        nama: '',
        score: 30
      }
    ],
    personalScore: [
      {
        num: 1,
        score: 50
      },
      {
        num: 2,
        score: 30
      },
      {
        num: 3,
        score: 10
      }
    ]
  },
  tiantiSnatchPoints: 1,
  acmTimePenalty: 20,
  duration: "",
}
const formRef = ref(null)
const rules = ref({
  title: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入标题",
  },
  auth: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请选择权限",
  },
  awardType: {
    required: true,
    trigger: ["blur", "input"],
    message: "请选择",
  },
  type: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请选择类型",
  },
  startTime: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请输入开始时间",
  },
  endTime: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请输入结束时间",
  },
})
const originRules = {
  title: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入标题",
  },
  auth: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请选择权限",
  },
  awardType: {
    required: true,
    trigger: ["blur", "input"],
    message: "请选择",
  },
  type: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请选择类型",
  },
  startTime: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请输入开始时间",
  },
  endTime: {
    type: "number",
    required: true,
    trigger: ["blur", "input"],
    message: "请输入结束时间",
  },
}
watch(
  () => raceData.value.endTime,
  () => {
    getDuration(raceData.value.startTime, raceData.value.endTime)
  }
)

watch(
  () => raceData.value.startTime,
  () => {
    getDuration(raceData.value.startTime, raceData.value.endTime)
  }
)

const getDuration = (pre, end) => {
  if (pre && end && end - pre > 0) {
    const duration = (end - pre) / 1000
    if (Math.floor(duration / 60) < 60) {
      raceData.value.duration = (duration / 60).toFixed(1) + "分钟"
      return
    }
    if (Math.floor(duration / 60 / 60) < 24) {
      raceData.value.duration = (duration / 60 / 60).toFixed(1) + "小时"
      return
    }
    raceData.value.duration = (duration / 60 / 60 / 24).toFixed(0) + "天"
  }
}

const appendAward = (value) => {
  if (value == 0) {
    if (!raceData.value.accountAwardConfig) {
      raceData.value.accountAwardConfig = []
      raceData.value.accountAwardConfig.push({
        backColor: "#000000",
        data: 1,
        level: 1,
        name: "",
      })
      return
    }
    if (raceData.value.accountAwardConfig.length >= 15) {
      ElMessage.error("个人奖项过多")
      return
    }
    raceData.value.accountAwardConfig.push({
      backColor: "#E9D343",
      data: "1",
      level:
        Number(
          raceData.value.accountAwardConfig[raceData.value.accountAwardConfig.length - 1].level
        ) + 1,
      name: "",
    })
  } else {
    if (!raceData.value.groupAwardConfig) {
      raceData.value.groupAwardConfig = []
      raceData.value.groupAwardConfig.push({
        backColor: "#E9D343",
        data: "1",
        level: 1,
        name: "",
      })
      return
    }
    if (raceData.value.groupAwardConfig.length >= 15) {
      ElMessage.error("团队奖项过多")
      return
    }
    raceData.value.groupAwardConfig.push({
      backColor: "#000000",
      data: "1",
      level: Number(
        raceData.value.groupAwardConfig[raceData.value.groupAwardConfig.length - 1].level
      ) + 1,
      name: "",
    })
  }

}
const delAward = (level, value = 0) => {
  if (value == 0) {
    if (raceData.value.accountAwardConfig.length <= 1) {
      ElMessage.error("至少保留一个 个人奖项")
      return
    }
    raceData.value.accountAwardConfig.forEach((ele, index) => {
      if (ele.level == level) {
        raceData.value.accountAwardConfig.splice(index, 1)
        return
      }
    })
  } else {
    if (raceData.value.groupAwardConfig.length <= 1) {
      ElMessage.error("至少保留一个 团队奖项")
      return
    }
    raceData.value.groupAwardConfig.forEach((ele, index) => {
      if (ele.level == level) {
        raceData.value.groupAwardConfig.splice(index, 1)
        return
      }
    })
  }

}

const handleValidateButtonClick = (e) => {
  e.preventDefault()
  //私有赛校验密码
  if (raceData.value.auth == 1) {
    rules.value.pwd = {
      required: true,
      trigger: ["blur", "input"],
      message: "请输入密码",
    }
  }
  //团队赛校验
  if (raceData.value.type == 1) {
    rules.value.groupUserMaxCount = {
      type: "number",
      required: true,
      trigger: ["blur", "input"],
      message: "请输入团队人数上限",
    }
    rules.value.groupRankType = {
      required: true,
      trigger: ["blur", "input"],
      message: "请选择团队排名方式",
    }
    rules.value.regStartTime = {
      type: "number",
      required: true,
      trigger: ["blur", "input"],
      message: "请输入报名开始时间",
    }
    rules.value.regEndTime = {
      type: "number",
      required: true,
      trigger: ["blur", "input"],
      message: "请输入报名结束时间",
    }
  }
  //ACM校验
  if (raceData.value.format == 0) {
    rules.value.acmTimePenalty = {
      type: "number",
      required: true,
      trigger: ["blur", "input"],
      message: "请设置ACM罚时",
    }
  }
  //天梯赛设置
  if (raceData.value.format == 3) {
    for (let i = 0; i < raceData.value.tiantiStageConfig.stage.length; i++) {
      const ele = raceData.value.tiantiStageConfig.stage[i]
      if (!ele.score || !ele.name) {
        ElMessage.error('请输入正确的阶段配置')
        return
      }
    }
    for (let i = 0; i < raceData.value.tiantiStageConfig.personalScore.length; i++) {
      const ele = raceData.value.tiantiStageConfig.personalScore[i]
      if (!ele.num || !ele.score) {
        ElMessage.error('请输入正确的先锋配置')
        return
      }
    }
  }
  //排行榜校验
  if (raceData.value.lockRank == 0) {
    rules.value.lockRankTime = {
      type: "number",
      required: true,
      trigger: ["blur", "input"],
      message: "请输入封榜时间",
    }
  }
  //个人奖项设置
  if (raceData.value.accountAwardType == 1 || raceData.value.accountAwardType == 2) {
    for (let i = 0; i < raceData.value.accountAwardConfig.length; i++) {
      const ele = raceData.value.accountAwardConfig[i]
      if (ele.name.length == 0 || ele.data == 0) {
        ElMessage.error("请输入正确的个人奖项参数")
        return
      }
    }
  }
  //团队奖项设置
  if (raceData.value.groupAwardType == 1 || raceData.value.groupAwardType == 2) {
    for (let i = 0; i < raceData.value.groupAwardConfig.length; i++) {
      const ele = raceData.value.groupAwardConfig[i]
      if (ele.name.length == 0 || ele.data == 0) {
        ElMessage.error("请输入正确的团队奖项参数")
        return
      }
    }
  }
  formRef.value?.validate((errors) => {
    if (!errors) {
      //有id说明为更新操作
      if (raceData.value.id.length > 0) {
        updateRace()
      } else {
        saveRace()
      }
    }
  })
  rules.value = originRules
}

//保存比赛
const saveRace = debounce(() => {
  rules.value = originRules
  const a = JSON.parse(JSON.stringify(raceData.value))
  stars.value.forEach((ele) => {
    a.starAccount.push(ele.uid)
  })
  starsGroup.value.forEach((ele) => {
    a.starGroup.push(ele.id)
  })
  a.starAccount = JSON.stringify(a.starAccount)
  a.starGroup = JSON.stringify(a.starGroup)
  a.accountAwardConfig = JSON.stringify(raceData.value.accountAwardConfig)
  a.groupAwardConfig = JSON.stringify(raceData.value.groupAwardConfig)
  a.startTime = getFormatDate(raceData.value.startTime)
  a.endTime = getFormatDate(raceData.value.endTime)
  if (raceData.value.type == 1) {
    a.regStartTime = getFormatDate(raceData.value.regStartTime)
    a.regEndTime = getFormatDate(raceData.value.regEndTime)
  } else {
    a.regStartTime = ""
    a.regEndTime = ""
  }
  if (raceData.value.lockRank == 0) {
    a.lockRankTime = getFormatDate(raceData.value.lockRankTime)
  } else {
    a.lockRankTime = ""
  }
  delete a.duration
  if (raceData.value.format == 3) {
    const arr1 = a.tiantiStageConfig.stage.map((v) => {
      return v.score
    })
    const arr3 = a.tiantiStageConfig.stage.map((v) => {
      return v.name
    })
    const arr2 = []
    for (let i = 0; i < a.tiantiStageConfig.personalScore.length; i++) {
      const element = a.tiantiStageConfig.personalScore[i]
      for (let j = 0; j < element.num; j++) {
        arr2.push(element.score)
      }
    }
    a.tiantiStageConfig.stage = arr1
    a.tiantiStageConfig.personalScore = arr2
    a.tiantiStageConfig.names = arr3
    a.tiantiStageConfig = JSON.stringify(a.tiantiStageConfig)
  } else {
    a.tiantiStageConfig = null
  }
  a.allowEndEntry = raceData.value.allowEndEntry
  appendRaceAPI(a)
    .then((res) => {
      if (res.data.code === 200) {
        raceData.value = raceOriginData
        ElMessage.success(res.data.msg)
        router.push({
          path: "/admin/race/list",
        })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 300)



//获取可打星用户
const isShowUsers = ref(false)
const users = ref({
  records: [],
  total: 10,
})
const searchParams = reactive({
  pageNum: 1,
  pageSize: 20,
  cid: "",
})
watch(searchParams, (newV) => {
  getUserInfoList()
})
const getUserInfoList = debounce(async () => {
  await getRaceUsersAPI(searchParams)
    .then((res) => {
      if (res.data.code === 200) {
        users.value = res.data.data
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 100)


//获取可打星团队
const isShowGroups = ref(false)
const groups = ref({
  records: [],
  total: 10,
})
const searchParams2 = reactive({
  pageNum: 1,
  pageSize: 20,
  cid: "",
})
watch(searchParams2, (newV) => {
  getGroupList()
})
const getGroupList = debounce(async () => {
  await getGroupListAPI(searchParams2).then((res) => {
    if (res.data.code === 200) {
      groups.value = res.data.data
      const temp = []
      let ids = starsGroup.value.map((v) => {
        return v.id
      })
      groups.value.records.forEach((ele) => {
        if (ids.includes(ele.id)) {
          temp.push(ele)
        }
      })
      starsGroup.value = temp
    }
  })
    .catch((err) => {
      console.log(err)
    })
}, 100)



const indexMethod = (index) => {
  return (searchParams.pageNum - 1) * searchParams.pageSize + index + 1
}
const stars = ref([])
const starsGroup = ref([])
const appendToStar = (data, value) => {
  if (value == 0) {//个人
    let flag = 0
    stars.value.forEach((ele) => {
      if (ele.username == data.username) {
        flag = 1
      }
    })
    if (flag == 0) {
      stars.value.push(data)
    }
  } else {//团队
    let flag = 0
    starsGroup.value.forEach((ele) => {
      if (ele.id == data.id) {
        flag = 1
      }
    })
    if (flag == 0) {
      starsGroup.value.push(data)
    }
  }
}
const handleClose = (username, value) => {
  if (value == 0) {
    stars.value.forEach((ele, index) => {
      if (ele.username == username) {
        stars.value.splice(index, 1)
        return
      }
    })
  } else {
    starsGroup.value.forEach((ele, index) => {
      if (ele.id == username) {
        starsGroup.value.splice(index, 1)
        return
      }
    })
  }

}
const getFormatDate = (time) => {
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0") // 月份从0开始，所以要加1
  const day = String(date.getDate()).padStart(2, "0")
  const hours = String(date.getHours()).padStart(2, "0")
  const minutes = String(date.getMinutes()).padStart(2, "0")
  const seconds = String(date.getSeconds()).padStart(2, "0")
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const getUnFormatTime = (time) => {
  const date = new Date(time)
  return Date.parse(date) || 0
}
//获取比赛详情
const getRaceDetail = debounce(async (cid) => {
  await getRaceDetailAPI(cid)
    .then((res) => {
      if (res.data.code === 200) {
        //个人奖项
        if (res.data.data.accountAwardConfig.length > 0) {
          res.data.data.accountAwardConfig = JSON.parse(res.data.data.accountAwardConfig)
          if (res.data.data.accountAwardConfig)
            res.data.data.accountAwardConfig = res.data.data.accountAwardConfig.map(v => {
              return {
                backColor: v.backColor,
                data: Number(v.data),
                level: Number(v.level),
                name: v.name,
              }
            })
        }
        //团队奖项
        if (res.data.data.groupAwardConfig.length > 0) {
          res.data.data.groupAwardConfig = JSON.parse(res.data.data.groupAwardConfig)
          if (res.data.data.groupAwardConfig)
            res.data.data.groupAwardConfig = res.data.data.groupAwardConfig.map(v => {
              return {
                backColor: v.backColor,
                data: Number(v.data),
                level: Number(v.level),
                name: v.name,
              }
            })
        }
        res.data.data.starAccount = JSON.parse(res.data.data.starAccount)
        res.data.data.starGroup = JSON.parse(res.data.data.starGroup)
        res.data.data.groupUserMaxCount = Number(res.data.data.groupUserMaxCount)
        if (res.data.data.format == 3 && res.data.data.tiantiStageConfig.length > 0) {
          res.data.data.tiantiStageConfig = JSON.parse(res.data.data.tiantiStageConfig)
          const arr1 = res.data.data.tiantiStageConfig.stage.map(v => {
            return { score: Number(v) }
          })
          let flag = 1
          const arr2 = []
          for (let i = 0; i < res.data.data.tiantiStageConfig.personalScore.length; i++) {
            const ele = res.data.data.tiantiStageConfig.personalScore[i]
            const ele1 = res.data.data.tiantiStageConfig.personalScore[i + 1]
            if (ele != ele1) {
              arr2.push({
                num: Number(flag),
                score: Number(ele)
              })
              flag = 1
            } else {
              flag += 1
            }
          }
          res.data.data.tiantiStageConfig.names.forEach((element, index) => {
            arr1[index].name = element
          })
          res.data.data.tiantiStageConfig.stage = arr1
          res.data.data.tiantiStageConfig.personalScore = arr2
        } else {
          res.data.data.tiantiStageConfig = {}
          res.data.data.tiantiStageConfig.stage = []
          res.data.data.tiantiStageConfig.personalScore = []
        }
        res.data.data.startTime = getUnFormatTime(res.data.data.startTime)
        res.data.data.endTime = getUnFormatTime(res.data.data.endTime)
        if (res.data.data.type == 1) {
          res.data.data.regStartTime = getUnFormatTime(
            res.data.data.regStartTime
          )
          res.data.data.regEndTime = getUnFormatTime(res.data.data.regEndTime)
        }
        res.data.data.lockRankTime = getUnFormatTime(
          res.data.data.lockRankTime
        )
        raceData.value = res.data.data
        stars.value.length = 0
        starsGroup.value.length = 0
        raceData.value.starAccount.forEach((ele) => {
          stars.value.push({
            username: ele,
          })
        })
        raceData.value.starGroup.forEach((ele) => {
          starsGroup.value.push({
            id: ele
          })
        })
        raceData.value.starAccount.length = 0
        raceData.value.starGroup.length = 0
        raceData.value.allowEndEntry = res.data.data.allowEndEntry ? 1 : 0
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 100)
onMounted(() => {
  if (route.name == "raceedit") {
    getRaceDetail(route.params.cid)
    searchParams.cid = route.params.cid
    searchParams2.cid = route.params.cid
  }
})
//更新比赛
const updateRace = debounce(async () => {
  const a = JSON.parse(JSON.stringify(raceData.value))
  if (stars.value.length > 0)
    stars.value.forEach((ele) => {
      a.starAccount.push(ele.username)
    })
  if (starsGroup.value.length > 0)
    starsGroup.value.forEach((ele) => {
      a.starGroup.push(ele.id)
    })
  a.starAccount = JSON.stringify(a.starAccount)
  a.starGroup = JSON.stringify(a.starGroup)
  a.accountAwardConfig = JSON.stringify(raceData.value.accountAwardConfig)
  a.groupAwardConfig = JSON.stringify(raceData.value.groupAwardConfig)
  a.startTime = getFormatDate(raceData.value.startTime)
  a.endTime = getFormatDate(raceData.value.endTime)
  if (raceData.value.type == 1) {
    a.regStartTime = getFormatDate(raceData.value.regStartTime)
    a.regEndTime = getFormatDate(raceData.value.regEndTime)
  } else {
    a.regStartTime = ""
    a.regEndTime = ""
  }
  if (raceData.value.lockRank == 0) {
    a.lockRankTime = getFormatDate(raceData.value.lockRankTime)
  } else {
    a.lockRankTime = ""
  }
  delete a.duration
  if (raceData.value.format == 3) {
    const arr1 = a.tiantiStageConfig.stage.map((v) => {
      return v.score
    })
    const arr3 = a.tiantiStageConfig.stage.map((v) => {
      return v.name
    })
    const arr2 = []
    for (let i = 0; i < a.tiantiStageConfig.personalScore.length; i++) {
      const element = a.tiantiStageConfig.personalScore[i]
      for (let j = 0; j < element.num; j++) {
        arr2.push(element.score)
      }
    }
    a.tiantiStageConfig.stage = arr1
    a.tiantiStageConfig.personalScore = arr2
    a.tiantiStageConfig.names = arr3
    a.tiantiStageConfig = JSON.stringify(a.tiantiStageConfig)
  } else {
    a.tiantiStageConfig = null
  }
  await updateRaceAPI(a)
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg)
        router.push({
          path: "/admin/race/list",
        })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}, 100)


const AwardTypeChange = () => {
  if (raceData.value.accountAwardType != 0 && (!raceData.value.accountAwardConfig || raceData.value.accountAwardConfig.length == 0)) {
    raceData.value.accountAwardConfig = [
      { backColor: "#F2EF09", data: "10", level: "1", name: "金牌" },
      { backColor: "#B1B2A8", data: "20", level: "2", name: "银牌" },
      { backColor: "#D4964B", data: "30", level: "3", name: "铜牌" },
    ]
    return
  } else if (raceData.value.groupAwardType != 0 && (!raceData.value.groupAwardConfig || raceData.value.groupAwardConfig.length == 0)) {
    raceData.value.groupAwardConfig = [
      { backColor: "#F2EF09", data: "10", level: "1", name: "金牌" },
      { backColor: "#B1B2A8", data: "20", level: "2", name: "银牌" },
      { backColor: "#D4964B", data: "30", level: "3", name: "铜牌" },
    ]
    return
  }
}


//天梯先锋分数设置
const appendtitianPersonal = () => {
  if (raceData.value.tiantiStageConfig.personalScore.length >= 20) {
    ElMessage.error('至多添加20个配置')
    return
  }
  raceData.value.tiantiStageConfig.personalScore.push({
    num: 1,
    score: 1
  })
}
const deltitianPersonal = (index) => {
  if (raceData.value.tiantiStageConfig.personalScore.length <= 3) {
    ElMessage.error("至少保留三个配置")
    return
  }
  raceData.value.tiantiStageConfig.personalScore.splice(index, 1)
}
//天梯阶段配置
const appendtitianStage = () => {
  if (raceData.value.tiantiStageConfig.stage.length >= 10) {
    ElMessage.error("最多配置10个阶段")
    return
  }
  raceData.value.tiantiStageConfig.stage.push({
    score: 10
  })
}
const deltitianStage = (index) => {
  if (raceData.value.tiantiStageConfig.stage.length <= 2) {
    ElMessage.error("至少保留两个阶段")
    return
  }
  raceData.value.tiantiStageConfig.stage.splice(index, 1)
}
</script>

<style lang="less" scoped>
.raceCreate {
  margin: auto;
  width: 96%;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 12px 12px 50px #d9d9d9, -12px -12px 50px #ffffff;
  display: flex;
  flex-direction: column;

  .r-header {
    display: flex;
    padding-bottom: 10px;
    border-bottom: 2px solid @lineColor;

    .r-h-title {
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #555;
      display: flex;
      text-align: center;

      .iconfont {
        margin: auto 0;
        font-weight: 700;
        font-size: 28px;
        height: 30px;
      }
    }
  }

  .form {
    margin-top: 20px;
    width: 100%;

    .datebox {
      display: flex;

      .date {
        width: 25%;
      }
    }

    .format {
      display: flex;

      .f-item {
        min-width: 18%;
        margin: auto 4% auto 0;
      }
    }

    .tianti {
      width: 50%;

      .table {
        width: 100%;
      }
    }

    .tianti2 {
      width: 70%;
      display: flex;

      .table {
        width: 80%;
      }

      .btns {
        width: 20%;
        padding: 1vh 1vw;
      }
    }

    .pane {
      display: flex;

      .pane-item {
        width: 15%;
      }
    }

    .awards {
      margin-bottom: 2vh;
    }

    .star {
      margin-top: 10px;

      .tag {
        margin: auto 3px;
      }
    }

    .private {
      display: flex;
      width: 100%;

      .p-item {
        width: 18%;
        margin: auto 4% auto 0;
      }
    }

    .short {
      width: 18%;
    }

    .lockRank {
      display: flex;

      .l-item {
        margin: auto 4% auto 0;
      }
    }

    .awardConfig {
      display: flex;

      .table {
        width: 90%;
      }

      .right-btns {
        width: 10%;
        display: flex;
        flex-direction: column;

        .btn {
          margin: 5px auto;
        }
      }
    }
  }

  .footer {
    display: flex;
    justify-content: center;

    .save {
      margin: 5vh 0 1vh 0;

      width: 10%;
    }
  }
}

.drawer {
  .table {
    height: 80vh;
  }

  .footer {
    display: flex;
    justify-content: center;
    margin: 5px 0;
  }
}
</style>
